package cn.yeziji.forum.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;

/**
 * bean 工具类
 *
 * @author gzkemays
 * @since 2022/1/13 21:38
 */
public class BeanUtils {
  private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

  public static <T> T getObjectFromMap(Map<String, Object> source, Class<T> clazz) {
    try {
      T target = clazz.newInstance();
      Field[] declaredFields = clazz.getDeclaredFields();
      for (Field field : declaredFields) {
        field.setAccessible(true);
        String name = field.getName();
        if (Objects.nonNull(source.get(name))) {
          field.set(target, source.get(field.getName()));
        }
      }
      return target;
    } catch (InstantiationException e) {
      logger.error("无参构造失败");
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      logger.error("实体类：" + clazz + "构造或传参出现异常");
      e.printStackTrace();
    }
    return null;
  }
}
